package com.hisense.ovcloud.acjulink.server;

import com.hisense.ovcloud.commons.configs.vertx.annotation.VerticleRegister;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.net.NetServer;
import io.vertx.core.net.NetServerOptions;
import io.vertx.core.parsetools.RecordParser;
import io.vertx.rxjava3.FlowableHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import static com.hisense.ovcloud.commons.constants.Constants.AcJulink.DATASEP;
import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE;


@Slf4j
@Component
@VerticleRegister
@Scope(SCOPE_PROTOTYPE)
public class JulinkSslServer extends AbstractVerticle {
    @Autowired
    private NetServerOptions options;

    @Override
    public void start() throws Exception {
        NetServer server = vertx.createNetServer(options);
        server.connectHandler(sock -> {
            // 设置分隔符
            RecordParser parser = RecordParser.newDelimited(DATASEP, sock);
            FlowableHelper.toFlowable(parser)
                    .map(buffer -> buffer.toString("UTF-8"))
                    .subscribe(msg -> sock.write(msg + "\n", "UTF-8"), throwable -> {
                        throwable.printStackTrace();
                        sock.close();
                    }, sock::close);

        }).listen(443);
        System.out.println("Start AcSslTcpServer!");
    }
}
